package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired//HttpServletRequest http请求协议对象
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.aspect.annotation.OperationLog)")
    public Object addLog(ProceedingJoinPoint pjp) {
        OperateLog operateLog = new OperateLog();
        log.info("OperationLogAspect.addLog");
        long start = System.currentTimeMillis();
        long end;
        // 获取请求头中的token
        String token = request.getHeader("token");
        System.out.println("在OperationLogAspect.addLog得到头中的token=" + token);
        // 获取类名
        String className = pjp.getTarget().getClass().getName();
        operateLog.setClassName(className);
        // 方法名
        String methodName = pjp.getSignature().getName();
        operateLog.setMethodName(methodName);
        // 方法参数列表
        Object[] args = pjp.getArgs();
        operateLog.setMethodParams(Arrays.toString(args));

        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //operateLog.setOperateEmpId(1);//TODO 先写死，后续处理
        Integer loginUserId = CurrentHolder.getCurrentId();
        operateLog.setOperateEmpId(loginUserId);
        //调用目标方法
        Object result;
        try {
            result = pjp.proceed();
            end = System.currentTimeMillis();
            //把返回值转成json字符串
            operateLog.setReturnValue(result.toString());
            return result;
        } catch (Throwable e) {
            operateLog.setReturnValue("出异常了!"+ e.getMessage());
            return null;
        } finally {
            end = System.currentTimeMillis();
            operateLog.setCostTime(end - start);//耗时
            //保存日志到数据库
            operateLogMapper.insert(operateLog);
        }

    }
}
